layui.config({base: '/static/js/'}).define(['form', 'layer', 'jquery', 'api'], function (exports) {
    var form = layui.form, layer = layui.layer, api = layui.api, $ = layui.jquery;

    var mditor = window.mditor = Mditor.fromTextarea(document.getElementById('md-editor'));
    mditor.split = false;
    mditor.on('ready', function () {
        var upload = function (file) {
            var name = file.name || 'screenshot.png';
            name = name.replace(/\.(?:jpg|gif|png)$/i, ''); // clear ext
            name = name.replace(/\W+/g, '_'); // clear unvalid chars
            file.name = name;
            var data = new FormData();
            data.append('file', file);
            $.ajax('/blog/uploadToCloud', {
                data: data,
                type: 'POST',
                processData: false,
                contentType: false
            }).done(function (res) {
                mditor.editor.insertBeforeText('![alt](' + res.data + ")\n");
            }).fail(function ($xhr) {
                if ($xhr.responseText) {
                    alert($xhr.responseText);
                }
            });
        };

        //示例，更改「图片」按钮配置，其它按钮是同样的方法
        var imgBtn = mditor.toolbar.getItem('image');
        //替换按钮动作
        imgBtn.handler = function () {
            var accept = {
                image: 'image/png,image/gif,image/jpg,image/jpeg'
            };
            var $file = $('<input type="file" accept="' + accept.image + '">');
            $file.click();
            $file.on('change', function () {
                var file = this.files[0];
                upload(file);
            });
        };
    });

    form.on("submit(publishBlog)", function (data) {
        var params = data.field;
        params['blog.pub'] = $("#switchPub").is(':checked');
        var content = mditor.value;
        if (content === null || content === '') {
            layer.msg("请输入文章内容", {shift: 6});
            return;
        }
        params['blog.content'] = content;
        api.publishBlog(params, function (res) {
            switch (res.code) {
                case 0:
                    var blogId = params["blog.id"];
                    if (blogId === null || blogId === '')
                        location.href = '/';
                    else
                        location.href = '/blog/view/' + blogId;
                    break;
                default:
                    layer.msg("发布失败", {shift: 6});
                    break;
            }
        });
        return false;
    });
});